package leetcode;


/**
 * 翻转字符串里的单词
 */
public class LeetCode151 {
    public String reverseWords(String s) {
        if (s == null || s.length() == 0) return s;
        StringBuilder result = new StringBuilder();
        int start = -1, end = -1;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                if (start == -1) continue;
                result.insert(0, (s.substring(start, end)) + " ");
                start = -1;
            } else {
                if (start == -1) start = end = i;
                end++;
            }
        }
        if (start != -1) result.insert(0, (s.substring(start, end)) + " ");
        if (result.length() == 0) return "";
        return result.subSequence(0, result.length() - 1).toString();
    }

}
